package com.chuangke.attachment.controller;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.chuangke.attachment.service.AttachmentService;
import com.chuangke.common.http.HttpResult;
import com.chuangke.common.utils.FileUtils;
import com.chuangke.file.model.FileType;
import com.chuangke.file.util.TikaUtil;

@RestController
@RequestMapping("attachment")
public class AttachmentController {

	@Autowired
	private AttachmentService attachmentService;

	@PreAuthorize("hasAuthority('login:action')")
	@PostMapping("upload/{id}")
	public HttpResult upload(@PathVariable("id") String id, MultipartFile file) {
		return HttpResult.ok(attachmentService.uploadAchievement(id, file));
	}

	/**
	 * 上传后存储到标准附件表
	 * @param id
	 * @param file
	 * @return
	 */
	@PreAuthorize("hasAuthority('login:action')")
	@PostMapping("uploadSys/{id}")
	public HttpResult uploadSys(@PathVariable("id") String id, MultipartFile file) {
		return HttpResult.ok(attachmentService.uploadSysAchievement(id, file));
	}
	
	/**
	 * 缩率图预览
	 * @param id
	 * @param response
	 */
//	@PreAuthorize("hasAuthority('login:action')")
	@GetMapping("thum/{id}")
	public void thum(@PathVariable("id") String id, HttpServletResponse response) {
		response.setContentType(FileType.jpg.getMime());
		byte[] fileBytes = attachmentService.previewThum(id);
		FileUtils.download(response, fileBytes);
	}
	
	/**
	 * 如果附件是图片，可以查看
	 * @param id
	 * @param response
	 */
	@GetMapping("view/{id}")
	public void view(@PathVariable("id") String id, HttpServletResponse response) {
		byte[] fileBytes = attachmentService.download(id) ;
		response.setContentType(TikaUtil.getMimeType(fileBytes));
//		response.setContentType(FileType.jpg.getMime());
		FileUtils.download(response, fileBytes);
	}

	@GetMapping("kkFileView/{id}/{fileName}")
	public void view(@PathVariable("id") String id,@PathVariable("fileName") String fileName, HttpServletResponse response) {
		byte[] fileBytes = attachmentService.download(id) ;
		response.setContentType(TikaUtil.getMimeType(fileBytes));
		FileUtils.download(response, fileBytes);
	}
	
	/**
	 * 下载附件
	 * @param id
	 * @param response
	 */
	@GetMapping("download/{id}")
	public void download(@PathVariable("id") String id, HttpServletResponse response) {
		FileUtils.download(response, attachmentService.download(id));
	}
}
